#include "chatroom.h"
#include <QVBoxLayout>

ChatRoom::ChatRoom(QStackedWidget *stackedWidget, QWidget *parent)
    : QWidget(parent), stackedWidget(stackedWidget)
{
    initUI();
    socket = new QTcpSocket(this);
    connect(socket, &QTcpSocket::readyRead, this, &ChatRoom::onReadyRead);
    socket->connectToHost("127.0.0.1", 1111);
    connect(sendButton, &QPushButton::clicked, this, &ChatRoom::sendMessage);
}

void ChatRoom::sendMessage()
{
    if (socket->state() == QTcpSocket::ConnectedState) {
        QString message = textEdit->toPlainText();
        if (!message.isEmpty()) {
            socket->write(message.toUtf8());
            socket->flush();
            textEdit->clear();
            messageShow->append("本人：" + message);
        }
    }
}

void ChatRoom::initUI()
{
    QVBoxLayout *layout = new QVBoxLayout;
    textEdit = new QTextEdit(this);
    messageShow = new QTextEdit(this);
    messageShow->setReadOnly(true);
    sendButton = new QPushButton(this);
    sendButton->setText("发送");
    layout->setSpacing(10);
    layout->addWidget(messageShow);
    layout->addWidget(textEdit);
    layout->addWidget(sendButton);
    this->setLayout(layout);
}

void ChatRoom::onReadyRead()
{
    QByteArray data = socket->readAll();
    QString message = QString::fromUtf8(data);
    qDebug() << "Received from server:" << message;
    messageShow->append(message);
}
